package com.chenzhou.qx.library.common.util;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * List工具
 *
 * @author tk
 * @date 2016/12/8
 */
public class ListUtil {

    /**
     * 产生随机集合
     *
     * @param list  data
     * @param count number
     * @return list
     */
    public static <T> List<T> getRandoms(List<T> list, int count) {

        List<T> labels = new ArrayList<>();
        if (list != null) {
            Random random = new Random();
            for (int i = 0; i < count; i++) {
                int r = random.nextInt(list.size());
                labels.add(list.get(r));
                list.remove(r);
            }
        }
        return labels;
    }

    /**
     * 分组
     *
     * @param resList 要拆分的集合
     * @param count   每个集合的元素个数
     * @return 返回拆分后的各个集合
     */
    public static <T> List<List<T>> split(List<T> resList, int count) {

        if (resList == null || count < 1) {
            return null;
        }
        List<List<T>> ret = new ArrayList<>();
        int size = resList.size();
        if (size <= count) {
            //数据量不足count指定的大小
            ret.add(resList);
        } else {
            int pre = size / count;
            int last = size % count;
            //前面pre个集合，每个大小都是count个元素
            for (int i = 0; i < pre; i++) {
                List<T> itemList = new ArrayList<>();
                for (int j = 0; j < count; j++) {
                    itemList.add(resList.get(i * count + j));
                }
                ret.add(itemList);
            }
            //last的进行处理
            if (last > 0) {
                List<T> itemList = new ArrayList<>();
                for (int i = 0; i < last; i++) {
                    itemList.add(resList.get(pre * count + i));
                }
                ret.add(itemList);
            }
        }
        return ret;

    }
}
